﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Domain.Extensions
{
	using System.Globalization;
	using System.Text;
	using System.Web.Mvc;
	using Falcon.Core.Extensions;

	public static class PollExtension
	{
		public const string BarLeft = "bar-left.png";
		public const string BarRight = "bar-right.png";
		public const string BarMiddle = "bar-middle.png";

		/// <summary>
		/// Gets the bar the image for the poll choice.
		/// </summary>
		/// <param name="choice">The choice.</param>
		/// <param name="poll">The poll.</param>
		/// <returns></returns>
		public static string BarImage(this PollChoice choice, Poll poll)
		{
			var builder = new StringBuilder();
			var percentage = poll.Percentage(choice);

			Append(builder, BarLeft);

			if (percentage > 0)
			{
				Append(builder, BarMiddle, (percentage * 2).ToString(CultureInfo.InvariantCulture));
			}

			Append(builder, BarRight);

			return builder.ToString();
		}

		/// <summary>
		/// Appends the specified image to the builder.
		/// </summary>
		/// <param name="builder">The builder.</param>
		/// <param name="bar">The bar.</param>
		private static void Append(StringBuilder builder, string bar)
		{
			Append(builder, bar, string.Empty);
		}

		/// <summary>
		/// Appends the specified image to the builder.
		/// </summary>
		/// <param name="builder">The builder.</param>
		/// <param name="bar">The bar.</param>
		/// <param name="width">The width.</param>
		private static void Append(StringBuilder builder, string bar, string width)
		{
			var img = new TagBuilder("img");

			img.MergeAttribute("src", string.Concat(Settings.Polls.ImagePath, "/", bar).AsRoot());
			img.MergeAttribute("width", width.HasValue() ? width : Settings.Polls.BarWidth);
			img.MergeAttribute("height", Settings.Polls.BarHeight);

			// append middle
			builder.Append(img.ToString(TagRenderMode.SelfClosing));
		}
	}
}